package cn.topcodes.tcsf.cms.web.controller;

import cn.topcode.unicorn.utils.RenderUtil;
import cn.topcode.unicorn.utils.UuidUtil;
import cn.topcode.unicorn.utils.ValidationUtil;
import cn.topcodes.tcsf.admin.commons.api.controller.admin.AdminController;
import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.admin.commons.api.security.ShiroUtil;
import cn.topcodes.tcsf.cms.domain.entity.Article;
import cn.topcodes.tcsf.cms.domain.form.ArticleForm;
import cn.topcodes.tcsf.cms.domain.vo.ArticleVo;
import cn.topcodes.tcsf.cms.service.ArticleService;
import cn.topcodes.tcsf.cms.service.ConfigService;
import cn.topcodes.tcsf.cms.utils.ActionMap;
import cn.topcodes.tcsf.cms.utils.FileUtils;
import cn.topcodes.tcsf.cms.utils.UEditor;
import cn.topcodes.tcsf.cms.utils.UEditorImageUpload;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * 文章管理控制器
 *
 * @author Unicorn
 * @date 2017-12-25 21:34:53
 */
@Controller
@RequestMapping("/admin/cms/article")
public class ArticleController extends AdminController<Article, ArticleVo, ArticleForm> {

    @Autowired
    private ConfigService configService;

    @Autowired
    private ArticleService articleService;

    @Override
    protected String getPageFolder() {
        return "/cms/article";
    }

    @RequestMapping("editor")
    public void editor(HttpServletResponse response,
                       HttpServletRequest request,
                       @RequestParam("action") String action) throws Exception {


        switch (action) {
            case ActionMap.CONFIG:
                loadConfig(request,response);
                break;
            case ActionMap.UPLOADIMAGE:
                ImageUpload(response, request, "cms-content-images");
                break;
            case ActionMap.UPLOADVIDEO:
                ImageUpload(response, request, "cms-content-video");
                break;
            case ActionMap.UPLOADFILE:
                fileUpload(response, request, "cms-content-file");
                break;
            default:
                break;
        }


    }


    /**
     * editor 加载后端配置项
     *
     * @param response
     * @throws IOException
     */
    public void loadConfig(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String path = this.getClass().getClassLoader().getResource("").getPath() + "/config.json";
        File file = new File(path);
        if (file.exists()) {
            String readFile = FileUtils.readFile(path);
            UEditor uEditor = JSONObject.toJavaObject(JSONObject.parseObject(readFile), UEditor.class);
            uEditor.setImageUrlPrefix("http://" + request.getServerName() + ":" + request.getServerPort()+ request.getContextPath()+"/");
            uEditor.setFileUrlPrefix("http://" + request.getServerName() + ":" + request.getServerPort()+ request.getContextPath()+"/");
            uEditor.setCatcherUrlPrefix("http://" + request.getServerName() + ":" + request.getServerPort()+ request.getContextPath()+"/");
            uEditor.setSnapscreenUrlPrefix("http://" + request.getServerName() + ":" + request.getServerPort()+ request.getContextPath()+"/");
            uEditor.setVideoUrlPrefix("http://" + request.getServerName() + ":" + request.getServerPort()+ request.getContextPath()+"/");
            uEditor.setFileManagerUrlPrefix("http://" + request.getServerName() + ":" + request.getServerPort()+ request.getContextPath()+"/");
            uEditor.setImageManagerUrlPrefix("http://" + request.getServerName() + ":" + request.getServerPort()+ request.getContextPath()+"/");
            RenderUtil.renderJson(uEditor, response);
        }
    }


    private void videoUpload(HttpServletResponse response, HttpServletRequest request, String filePath) {
    }

    /**
     * 富文本编辑器文件上传功能
     *
     * @param response
     * @param request
     * @param filePath
     * @throws IOException
     */
    public void ImageUpload(HttpServletResponse response, HttpServletRequest request, String filePath) throws IOException {
        String basePath = configService.getFileFolderPath();
        UEditorImageUpload uEditorImageUpload = new UEditorImageUpload();
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
            List<MultipartFile> fileRows = multiRequest
                    .getFiles(iter.next().toString());
            if (fileRows != null && fileRows.size() != 0) {
                if (fileRows.get(0) != null) {
                    String imgPath = filePath + "/" + UuidUtil.getUUID() + "." + fileRows.get(0).getOriginalFilename().substring(fileRows.get(0).getOriginalFilename().lastIndexOf(".") + 1);
                    org.apache.commons.io.FileUtils.copyInputStreamToFile(fileRows.get(0).getInputStream(), new File(basePath + imgPath));
                    uEditorImageUpload.setOriginal(fileRows.get(0).getOriginalFilename());
                    uEditorImageUpload.setTitle(fileRows.get(0).getOriginalFilename());
                    uEditorImageUpload.setSize(fileRows.get(0).getSize());
                    uEditorImageUpload.setState("SUCCESS");
                    uEditorImageUpload.setType("." + fileRows.get(0).getOriginalFilename().substring(fileRows.get(0).getOriginalFilename().lastIndexOf(".") + 1));
                    uEditorImageUpload.setUrl(OtherController.FILE_PATH + "?path=" + imgPath);
                }
            }
        }
        RenderUtil.renderJson(uEditorImageUpload, response);
    }

    /**
     * 富文本编辑器文件上传功能
     *
     * @param response
     * @param request
     * @param filePath
     * @throws IOException
     */
    public void fileUpload(HttpServletResponse response, HttpServletRequest request, String filePath) throws IOException {
        String basePath = configService.getFileFolderPath();
        UEditorImageUpload uEditorImageUpload = new UEditorImageUpload();
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
            List<MultipartFile> fileRows = multiRequest
                    .getFiles(iter.next().toString());
            if (fileRows != null && fileRows.size() != 0) {
                if (fileRows.get(0) != null) {
                    String imgPath = filePath + "/" + UuidUtil.getUUID() + "." + fileRows.get(0).getOriginalFilename().substring(fileRows.get(0).getOriginalFilename().lastIndexOf(".") + 1);
                    org.apache.commons.io.FileUtils.copyInputStreamToFile(fileRows.get(0).getInputStream(), new File(basePath + imgPath));
                    uEditorImageUpload.setOriginal(fileRows.get(0).getOriginalFilename());
                    uEditorImageUpload.setTitle(fileRows.get(0).getOriginalFilename());
                    uEditorImageUpload.setSize(fileRows.get(0).getSize());
                    uEditorImageUpload.setState("SUCCESS");
                    uEditorImageUpload.setType("." + fileRows.get(0).getOriginalFilename().substring(fileRows.get(0).getOriginalFilename().lastIndexOf(".") + 1));
                    uEditorImageUpload.setUrl(OtherController.FILEVIDEO_PATH + "?path=" + imgPath);
                }
            }
        }
        RenderUtil.renderJson(uEditorImageUpload, response);
    }

    @Override
    public ApiResponseEntity create(HttpServletRequest request, @Valid @ApiParam("创建资源表单") ArticleForm form, BindingResult result) {
        ValidationUtil.validate(result);
        Article entity = this.form2Entity(form);
        entity.setAuthor(ShiroUtil.getName());
        entity.setIsTop(form.getIsTop() == null ? false : true);
        entity.setIsShow(form.getIsShow() == null ? false : true);
        entity.setIsComment(form.getIsComment() == null ? false : true);
        entity.setPv(0L);
        Long id = articleService.create(entity);
        return ApiResponseEntity.buildOK().setBody(id);
    }

    @Override
    protected void entity2VoDiff(Article entity, ArticleVo vo) {
        vo.setContent(StringEscapeUtils.unescapeHtml4(entity.getContent()));
        super.entity2VoDiff(entity, vo);
    }
}
